import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import PublicActivitiesView from '../views/PublicActivitiesView.vue';
import ActivityDetailView from '../views/ActivityDetailView.vue';
import ActivityManagementView from '../views/ActivityManagementView.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities/:id',
    name: 'activity-detail',
    component: ActivityDetailView,
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: { requiresAuth: true, requiresAdmin: true }
  }
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  const userRole = localStorage.getItem('userRole');
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin);

  if (requiresAuth && !userRole) {
    next('/login');
  } else if (requiresAdmin && userRole !== 'admin') {
    alert('无权限访问该页面');
    next('/');
  } else {
    next();
  }
});

export default router;